package org.example.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("webflux")
public class FileUploadController {

    @PostMapping("/upload")
    public Mono<ResponseEntity<String>> uploadFile(@RequestPart("file") FilePart filePart) {
        // 文件传输下载
        String fileName = UUID.randomUUID().toString();
        Path tempFilePath = Paths.get("C:\\dev\\pressTest\\webflux\\" + fileName + ".tar");

        return filePart.transferTo(tempFilePath)
                .then(Mono.just(new ResponseEntity<>("WebFlux File '" + filePart.filename() + "' uploaded.", HttpStatus.OK)))
                .onErrorResume(
                        e -> Mono.just(new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR))
                );
    }
}
